#include<iostream>
#include<vector>
#include<queue>
using namespace std;
queue<pair<int, int>> q;
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,1,-1 };
int step = -1;
int rotApple(vector<vector<int> >& grid) {
    // write code here
    int n = grid.size();
    int m = grid[0].size();
    for (int i = 0; i < n; i++) 
    {
        for (int j = 0; j < m; j++) 
        {
            if (grid[i][j] == 2) 
            {
                q.push({ i,j });
            }
        }
    }
    if (q.empty()) return -1;
    while (!q.empty()) 
    {
        int se = q.size();
        step++;
        for (int i = 0; i < se; i++) 
        {
            int next_x = 0;
            int next_y = 0;
            pair<int, int> a = q.front();
            q.pop();
            int x = a.first;
            int y = a.second;
            for (int k = 0; k < 4; k++) 
            {
                 next_x = x + dx[k];
                 next_y = y + dy[k];
                 if (next_x >= 0 && next_x < n
                     && next_y >= 0 && next_y < m
                     && grid[next_x][next_y] == 1)
                 {
                     grid[next_x][next_y] = 2;
                     q.push({ next_x,next_y });
                 }
            }    
        }
      
    }
    return step;
}
//int main() 
//{
//    vector<vector<int>> grid = { {2,1,1},{1,0,1},{1,1,1 } };
//    int ret = rotApple(grid);
//    cout << ret;
//    return 0;
//}